package com.water.bs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.water.bs.pojo.ChangeApply;
import com.water.bs.pojo.ChangeInfo;
import com.water.bs.pojo.User;
import com.water.bs.service.UserChangeService;
import com.water.bs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@RestController
@CrossOrigin
public class UserChangeController {
    @Autowired
    private UserChangeService userChangeService;
    @Autowired
    private UserService userService;

    @RequestMapping("/makeChange")
    public JSON makeChange(@RequestBody JSONObject changeInfo){
        JSONObject rs = new JSONObject();
        System.out.println(changeInfo);
        Map<String,Object> map = new HashMap<>();
        map=changeInfo;
        map.put("id", UUID.randomUUID().toString());
        map.put("complete",0);//创建后 complete为0 未完成状态  交换成功后才是1
        map.put("createtime",System.currentTimeMillis());
        System.out.println(map);
        int i = userChangeService.makeChange(map);
        if (i>0){
            rs.put("state","0");
            rs.put("message","基本信息创建完成,请尽快添加一个图片!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","创建失败！");
            return rs;
        }

    }

    @RequestMapping("/qryMyChange")
    public JSON qryMyChange(@RequestParam("id")String id){
        JSONObject rs = new JSONObject();
        System.out.println(id);
        List<ChangeInfo> changeInfos = userChangeService.qryMyChange(id);
        rs.put("state","0");
        rs.put("message","更新成功!");
        rs.put("data",changeInfos);
        return rs;
    }

    @RequestMapping("/getChangeInfoPhoto")
    public void getChangeInfoPhoto(@RequestParam("id")String id, final HttpServletResponse response) throws IOException {
        ChangeInfo changeInfo = userChangeService.getChaneInfoById(id);
        byte[] data = changeInfo.getPhoto();
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
    }

    @RequestMapping("/getChaneInfoById")
    public JSONObject getChaneInfoById(@RequestParam("id")String id) throws IOException {
        JSONObject rs = new JSONObject();
        ChangeInfo changeInfo = userChangeService.getChaneInfoById(id);
        User userById = userService.getUserById(changeInfo.getCreaterid());
        Map<String,Object> map = new HashMap<>();
        map.put("nickname",userById.getNickname());
        map.put("address",userById.getAddress());
        map.put("city",userById.getCity());
        map.put("changeinfoid",changeInfo.getId());
        map.put("mytype",changeInfo.getMytype());
        map.put("wanttype",changeInfo.getWanttype());
        map.put("title",changeInfo.getTitle());
        map.put("message",changeInfo.getMessage());
        map.put("createrid",changeInfo.getCreaterid());
        map.put("complete",changeInfo.getComplete());
        map.put("id",changeInfo.getId());
        rs.put("data",map);
        return rs;
    }

    @RequestMapping("/saveChangeInfoPhoto")
    public JSON savePhoto(@RequestParam("file") MultipartFile file, @RequestParam("id") String id){
        JSONObject rs = new JSONObject();
        System.out.println(file);
        System.out.println(id);
        Map<String,Object> map = new HashMap<>();
        if (file.isEmpty()){
            rs.put("state","1");
            rs.put("message","上传失败,请重新选择!");
            return rs;
        }
        try {
            InputStream is = file.getInputStream();
            byte[] photoFile = new byte[(int)file.getSize()];
            System.out.println("图片大小:"+file.getSize());
            is.read(photoFile);

            map.put("photo",photoFile);
            map.put("id",id);

            int i = userChangeService.saveChangeInfoPhoto(map);
            if (i>0){
                rs.put("state","0");
                rs.put("message","保存成功");
            }else{
                rs.put("state","1");
                rs.put("message","上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rs;

    }

    @RequestMapping("/deleteChangeInfo")
    public JSON deleteChange(@RequestParam("id")String id){
        System.out.println("需要删除的changeid:"+id);
        JSONObject rs = new JSONObject();
        int i = userChangeService.deleteChangeInfo(id);
        if (i>0){
            rs.put("state","0");
            rs.put("message","删除成功!");
            return  rs;
        }else{
            rs.put("state","1");
            rs.put("message","删除信息失败!");
            return  rs;
        }
    }

    @RequestMapping("qryAllChangeXme") //用户查询除了自己的物品信息 以及已经申请过的物品信息
    public JSON qryAllChange (@RequestParam("id")String id){
        JSONObject rs = new JSONObject();
       List< Map<String,Object>> changeInfos = null;
        changeInfos = userChangeService.qryAllChangeXme(id);
        System.out.println("交换物品列表是"+changeInfos);
        //数据格式 {city=江苏省无锡市崇安区, nickname=超级无敌水王, mytype=数码手机, id=5a86075d-cc7c-4cb6-aaf6-33c703722a65, createrid=123123AAAAAA, wanttype=百货123123, title=测试同意后拒绝其他人, message=测试同意后拒绝其他人}

        Map<String,Object> map = new HashMap<>();
        for (Map<String, Object> changeInfo : changeInfos) {
            map.put("changeinfoid",changeInfo.get("id"));
            map.put("userid",id);
            int i = userChangeService.qryIsLike(map);
            changeInfo.put("like",i);
        }


        rs.put("data",changeInfos);
        return rs;
    }


    @RequestMapping("makeApplyChange") //创建交换申请 保存发起者id,保存发起者的物品id，被交换的物品id，交换类型0-等待，1同意 2拒绝 ,本条交换申请的订单id
    public JSON makeApplyChange (@RequestBody JSONObject applyChangeInfo){
        JSONObject rs = new JSONObject();
        System.out.println(applyChangeInfo);
        Map<String,Object> map = new HashMap<>();
        map=applyChangeInfo;
        map.put("changetype",0); //一开始 0  等待被交换者同意或拒绝
        map.put("id",UUID.randomUUID().toString());
        map.put("createtime",System.currentTimeMillis());
        System.out.println(map);
        int i = userChangeService.makeApplyChange(map);
        if (i>0){
            rs.put("state","0");
           return rs;
        }else{
            rs.put("state","1");
            return rs;
        }
    }


    @RequestMapping("/qryMyApply")
    public JSON qryApply(@RequestParam("id")String id){
        JSONObject rs = new JSONObject();
        System.out.println("qryMyApply:"+id);
        List<Map<String,Object>> changeApplies = userChangeService.qryMyApply(id);
        List<Map<String,Object>> rsList = new ArrayList<>(changeApplies.size());

        for (int i = 0; i < changeApplies.size(); i++) {
            System.out.println(changeApplies.get(i));
            Map<String, Object> map1 = userChangeService.qryMyApply2((String) changeApplies.get(i).get("applychangeinfoid"));
            Map<String, Object> map2 = userChangeService.qryMyApply3((String) changeApplies.get(i).get("respondentchangeinfoid"));
            Map<String, Object> rsMap = new HashMap<>();
            if (map1 ==null ||map2==null){
                rs.put("state","1");
                rs.put("message","信息异常！");
                return rs;
            }
            User userById = userService.getUserById((String) changeApplies.get(i).get("responderid"));
            rsMap.put("city",userById.getCity());
            rsMap.put("address",userById.getAddress());
            rsMap.putAll(map1);
            rsMap.putAll(map2);
            rsMap.put("changetype",changeApplies.get(i).get("changetype"));
            rsMap.put("applychangeinfoid",changeApplies.get(i).get("applychangeinfoid"));
            rsMap.put("respondentchangeinfoid",changeApplies.get(i).get("respondentchangeinfoid"));
            rsMap.put("applyerid",id);
            rsMap.put("responderid",changeApplies.get(i).get("responderid"));
            rsMap.put("id",changeApplies.get(i).get("id"));
            rsMap.put("applyerexpressid",changeApplies.get(i).get("applyerexpressid"));
            rsMap.put("responderexpressid",changeApplies.get(i).get("responderexpressid"));
            rsMap.put("createtime",changeApplies.get(i).get("createtime"));

            System.out.println(rsMap);
            rsList.add(rsMap);
        }
        rs.put("data",rsList);
        return rs;
    }
    //3.9---
    @RequestMapping("/qryMyRespondent")
    public JSON qryMyRespondent(@RequestParam("id")String id){
        JSONObject rs = new JSONObject();
        System.out.println("qryMyRespondent:"+id);
        List<ChangeApply> changeApplies = userChangeService.qryMyRespondent(id);
        List<Map<String,Object>> rsList = new ArrayList<>(changeApplies.size());

        for (int i = 0; i < changeApplies.size(); i++) {
            System.out.println(changeApplies.get(i));
            Map<String, Object> map1 = userChangeService.qryMyApply2(changeApplies.get(i).getApplychangeinfoid());
            Map<String, Object> map2 = userChangeService.qryMyApply3(changeApplies.get(i).getRespondentchangeinfoid());
            Map<String, Object> rsMap = new HashMap<>();
            if (map1 ==null ||map2==null){
                rs.put("state","1");
                rs.put("message","信息异常！");
                return rs;
            }
            rsMap.putAll(map1);
            rsMap.putAll(map2);
            rsMap.put("changetype",changeApplies.get(i).getChangetype());
            rsMap.put("applychangeinfoid",changeApplies.get(i).getApplychangeinfoid());
            rsMap.put("respondentchangeinfoid",changeApplies.get(i).getRespondentchangeinfoid());
            rsMap.put("applyerid",changeApplies.get(i).getApplyerid());
            rsMap.put("responderid",id);

            rsMap.put("id",changeApplies.get(i).getId());
            User userById = userService.getUserById(changeApplies.get(i).getApplyerid());
            rsMap.put("city",userById.getCity());
            rsMap.put("address",userById.getAddress());
            rsMap.put("applyerexpressid",changeApplies.get(i).getApplyerexpressid());
            rsMap.put("responderexpressid",changeApplies.get(i).getResponderexpressid());
            System.out.println(rsMap);
            rsList.add(rsMap);
        }
        rs.put("data",rsList);
        return rs;

    }
    @RequestMapping("/updateChangeInfo")
    public JSON updateChangeInfo(@RequestBody JSONObject editChangeInfo){
        JSONObject rs = new JSONObject();
        Map<String,Object> map = new HashMap<>();
        System.out.println(editChangeInfo);
        map.put("id",editChangeInfo.get("id"));

        if (editChangeInfo.get("mytype")!=null){
            map.put("mytype", editChangeInfo.get("mytype"));
        }

        if (editChangeInfo.get("wanttype")!=null){
            map.put("wanttype", editChangeInfo.get("wanttype"));
        }

        if (editChangeInfo.get("message")!=null){
            map.put("message", editChangeInfo.get("message"));
        }
        if (editChangeInfo.get("title")!=null){
            map.put("title", editChangeInfo.get("title"));
        }

        System.out.println(map);
        int i = userChangeService.updateChangeInfo(map);
        if (i ==1){
            rs.put("state","0");
            rs.put("message","修改完成!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","物品不存在或信息错误!");
            return rs;
        }

    }


    @RequestMapping("/cancelMyChangeApply")
    public JSON cancelMyChangeApply(@RequestParam("changeApplyId")String changeApplyId){
        System.out.println("要取消的changeapply的id是"+changeApplyId);
        JSONObject rs = new JSONObject();
        int i = userChangeService.cancelMyChangeApply(changeApplyId);
        if (i>0){
            rs.put("state","0");
            rs.put("message","操作成功!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","操作失败!");
            return rs;
        }

    }


    @RequestMapping("/agreeMyChangeRespondent")
    public JSON agreeMyChangeRespondent (@RequestBody JSONObject agreenInfo){
        System.out.println(agreenInfo);
        JSONObject rs = new JSONObject();
        int i = userChangeService.agreeMyChangeRespondent(agreenInfo);
        if (i>0){
            //修完完成changeapply中的changetype 接着修改 2个物品的 chaninfo的complete
            Map<String,Object>map = new HashMap<>();
            map.put("id",agreenInfo.get("respondentchangeinfoid")); //被申请人就是我。修改我的物品complete为1完成
            map.put("complete",1);
            int i1 = userChangeService.updateChangeInfo(map);
            if (i1>0) {
                //修改完我的物品后修改申请者的物品complete也是1
                map.put("id", agreenInfo.get("applychangeinfoid"));
                int i2 = userChangeService.updateChangeInfo(map);
                if (i2 > 0) {
                    //同意别人的申请 的同时 把其他人的申请这个物品的type改成取消
                    Map<String,Object> map2 = new HashMap<>();
                    map2.put("respondentchangeinfoid",agreenInfo.get("respondentchangeinfoid"));
                    map2.put("applychangeinfoid",agreenInfo.get("applychangeinfoid"));

                    userChangeService.agreeMyChangeRespondent2(map2);
//                    同意交换后 这2个物品 的所有参与的申请与被申请都应该修改成取消
                    Map<String,Object> map3 = new HashMap<>();
                    map3.put("changeinfoid1",agreenInfo.get("respondentchangeinfoid"));
                    map3.put("changeinfoid2",agreenInfo.get("applychangeinfoid"));
                    map3.put("id", agreenInfo.get("id"));
                    userChangeService.agreeMyChangeRespondent3(map3);

                    rs.put("state", "0");
                    rs.put("message", "操作完成!");
                    return rs;
                }
            }
        }
        rs.put("state","1");
        rs.put("message","操作失败!");
        return rs;
    }

    @RequestMapping("/rejectMyChangeRespondent")
    public JSON rejectMyChangeRespondent (@RequestBody JSONObject rejectInfo){
        JSONObject rs = new JSONObject();
        System.out.println(rejectInfo);
        int i = userChangeService.rejectMyChangeRespondent(rejectInfo);
        if (i>0){
            //修完完成changeapply中的changetype为2表示拒绝
            rs.put("state","0");
            rs.put("message","操作成功!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","操作失败!");
            return rs;
        }

    }

    @RequestMapping("/saveapplyerexpressid")
    public JSON saveapplyerexpressid(@RequestBody JSONObject applyerexpressinfo){
        JSONObject rs = new JSONObject();
        System.out.println(applyerexpressinfo);
        Map<String,Object> map = new HashMap<>();
        map = applyerexpressinfo;
        int i = userChangeService.saveapplyerexpressid(map);
        if(i>0){
            rs.put("state","0");
            rs.put("message","保存物流编号完成!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","保存物流编号失败!");
            return rs;
        }

    }

    @RequestMapping("/saveresponderexpressid")
    public JSON saveresponderexpressid(@RequestBody JSONObject responderexpressinfo){
        JSONObject rs = new JSONObject();
        System.out.println(responderexpressinfo);
        Map<String,Object> map = new HashMap<>();
        map = responderexpressinfo;
        int i = userChangeService.saveresponderexpressid(map);
        if(i>0){
            rs.put("state","0");
            rs.put("message","保存物流编号完成");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","保存物流编号失败!");
            return rs;
        }

    }

    @RequestMapping("/saveLike") //通过like字段判断收藏或者取消 1收藏 0 取消
    public JSON saveLike(@RequestBody JSONObject likeInfo){
        JSONObject rs = new JSONObject();
        System.out.println(likeInfo);
        userChangeService.saveLike(likeInfo);
        return rs;
    }

    @RequestMapping("/qryMyLike") //查询我的收藏
    public JSON qryMyLike(@RequestParam("id")String id){
        JSONObject rs = new JSONObject();
        System.out.println("我的收藏:我的id"+id);
        List<Map<String, Object>> maps = userChangeService.qryMyLike(id);
        rs.put("data",maps);
        return rs;
    }

    @RequestMapping("/allChangeHistory")
    public  JSON allChangeHistory(){
        JSONObject rs = new JSONObject();
        List<Map<String, Object>> maps = userChangeService.allChangeHistory();
        for (Map<String, Object> map : maps) {
            String applyernickname = userService.getUserById((String) map.get("applyerid")).getNickname();
            map.put("applyernickname",applyernickname);
            String respondernick = userService.getUserById((String) map.get("responderid")).getNickname();
            map.put("respondernickname",respondernick);
        }

        rs.put("data",maps);
        return rs;
    }

}
